package appfuse.framework.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.rmi.server.UID;
import java.sql.Timestamp;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import magick.ImageInfo;
import magick.MagickImage;

import org.apache.struts.upload.FormFile;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * <p>Title: 提供的一些实用的帮助方法</p>
 * <p>Description: 一些实用的帮助方法</p>
 * <p>Copyright: Kingsoft Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author savage
 * @version 1.0
 */
public class Helper {

	/**
	 * 将字符串类型转为日期类型
	 * @param str String
	 * @return Date
	 */
	public static Date str2Date(String str) {
		Date d = null;
		SimpleDateFormat formatter = new SimpleDateFormat(
		"yyyy-MM-dd");
		try {
			d = formatter.parse(str);
		} catch (ParseException pe) {
			//log.error(pe, pe.fillInStackTrace());
		}
		return d;
	}

	/**
	 * 判断该字符串是否是日期格式
	 * @param str String
	 * @return boolean
	 */
	public static boolean isDate(String str) {
		boolean bReturn = false;
		SimpleDateFormat formatter = new SimpleDateFormat(
		"yyyy-MM-dd");
		try {
			formatter.parse(str);
			bReturn = true;
		} catch (ParseException pe) {
			//
		} finally {
		}
		return bReturn;
	}

	/**
	 * 判断该字符串是否是Timestamp格式
	 * @param str String
	 * @return boolean
	 */
	public static boolean isTimestamp(String str) {
		boolean bReturn = false;
		SimpleDateFormat formatter = new SimpleDateFormat(
		"yyyy-MM-dd HH:mm:ss");
		try {
			formatter.parse(str);
			bReturn = true;
		} catch (ParseException pe) {
			//
		} finally {
		}
		return bReturn;

	}

	/**
	 * 十六进制转二进制
	 * @param str String
	 * @return String
	 */
	public static String hex2Bin(String str) {
		//十六进制转二进制
		if (str == null) {
			str = "";
		}
		StringBuffer strReturn = new StringBuffer();
		String strTemp = str.toUpperCase();
		for (int i = 0; i < strTemp.length(); i++) {
			char chr = strTemp.charAt(i);
			if ( (chr >= 48 && chr <= 57)
					|| (chr >= 65 && chr <= 70)) {
				if (chr == 'A') {
					strReturn.append("1010");
				} else if (chr == 'B') {
					strReturn.append("1011");
				} else if (chr == 'C') {
					strReturn.append("1100");
				} else if (chr == 'D') {
					strReturn.append("1101");
				} else if (chr == 'E') {
					strReturn.append("1110");
				} else if (chr == 'F') {
					strReturn.append("1111");
				} else if (chr == '0') {
					strReturn.append("0000");
				} else if (chr == '1') {
					strReturn.append("0001");
				} else if (chr == '2') {
					strReturn.append("0010");
				} else if (chr == '3') {
					strReturn.append("0011");
				} else if (chr == '4') {
					strReturn.append("0100");
				} else if (chr == '5') {
					strReturn.append("0101");
				} else if (chr == '6') {
					strReturn.append("0110");
				} else if (chr == '7') {
					strReturn.append("0111");
				} else if (chr == '8') {
					strReturn.append("1000");
				} else if (chr == '9') {
					strReturn.append("1001");
				}
			} else {
				strReturn.append("0000");
			}
		}
		return strReturn.toString();
	}

	/**
	 * 二进制转十六进制
	 * @param str String
	 * @return String
	 */
	public static String bin2Hex(String str) {
		//二进制转十六进制
		StringBuffer sb = new StringBuffer();
		sb.append(str);
		String strUnit = "00000000000000000000000000000000";
		if (sb == null) {
			//128位的0值
			sb.append(strUnit).append(strUnit).append(strUnit).append(strUnit);
		}
		//补齐128位
		int length = sb.length();
		if (length < 128) {
			for (int i = 0; i < 128 - length; i++) {
				sb.append('0');
			}
		}
		StringBuffer sbResult = new StringBuffer();
		for (int i = 0; i < sb.length(); i += 4) {
			String strTemp = new String();
			strTemp = sb.toString().substring(i, i + 4);
			sbResult.append(Integer.toHexString(Integer.parseInt(Integer.
					valueOf(
							strTemp, 2).toString())));
		}
		return sbResult.toString();
	}

	/**
	 * 将字符串更据"|"转化为数组
	 * @param str String
	 * @return String[]
	 */
	public static String[] str2Array(String str) {
		String strSrc = new String(hex2Bin(str));
		String[] strDest = new String[strSrc.length()];
		for (int i = 0; i < strSrc.length(); i++) {
			if (strSrc.charAt(i) == '1') {
				strDest[i] = new Integer(i + 1).toString();
			}
		}
		return strDest;
	}

	/**
	 * 将bigDecimal类型转化为Long
	 * @param bd BigDecimal
	 * @return long
	 */
	public static long bigDecimal2Long(BigDecimal bd) {
		long result = 0;
		try {
			if (bd != null) {
				result = Long.parseLong(bd.toString());
			}
		} catch (NumberFormatException nfe) {
			result = 0;
		}
		return result;
	}

	/**
	 * 转化字符串为UTF8编码
	 * @param s String
	 * @return String
	 */
	public static String Str2UTF8(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					//b = Character.toString(c).getBytes("utf-8");
					//1.3版本不支持Character.toString(c)改用以下方法
					b = new Character(c).toString().getBytes("utf-8");
				} catch (Exception ex) {
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0) {
						k += 256;
					}
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}

	/**
	 * 将UTF8格式转化
	 * @param s String
	 * @return String
	 */
	public static String UTF82Str(String s) {

		StringBuffer sb = new StringBuffer();
		byte[] b = new byte[3];
		int temp;
		int index;
		try {
			while (s.length() != 0) {
				index = s.indexOf("%");
				if (index == -1) {
					return sb.append(s).toString();
				}
				if (index != 0) {
					sb.append(s.substring(0, index));
				}
				if (index + 9 <= s.length()) {
					temp =
						Integer.parseInt(s.substring(index + 1, index + 3), 16)
						- 256;
					b[0] = Byte.parseByte(String.valueOf(temp));
					temp =
						Integer.parseInt(s.substring(index + 4, index + 6), 16)
						- 256;
					b[1] = Byte.parseByte(String.valueOf(temp));
					temp =
						Integer.parseInt(s.substring(index + 7, index + 9), 16)
						- 256;
					b[2] = Byte.parseByte(String.valueOf(temp));

					sb.append(new String(b, "UTF-8"));
					index += 9;
					s = s.substring(index);
				} else {
					return null;
				}
			}
		} catch (UnsupportedEncodingException ue) {
			
		} catch (NumberFormatException ne) {
			
		}
		return sb.toString();
	}

	/**
	 * 分解字符串
	 * @param s String
	 * @param l String
	 * @return String[]
	 */
	public static String[] splitStr(String s, String l) {
		StringTokenizer st = new StringTokenizer(s, l);
		String str[] = new String[st.countTokens()];
		String temp = "";
		int i = 0;
		while (st.hasMoreTokens()) {
			temp = st.nextToken();
			str[i] = temp;
			i++;
		}
		return str;
	}

	/**
	 * 将字符串ISO编码
	 * @param s String
	 * @return String
	 */
	public static String str2ISO(String s) {
		String result = "";
		try {
			result = new String(s.getBytes("GBK"), "ISO8859-1");
		} catch (UnsupportedEncodingException ex) {
		}
		return result;
	}

	/**
	 * 替换指定的字符
	 * @param source StringBuffer
	 * @param strS String
	 * @param strD String
	 * @return StringBuffer
	 */
	public static StringBuffer replaceAll(StringBuffer source, String strS,
			String strD) {
		if (strS.equals(strD) || strS.length() == 0) {
			return source;
		}
		int start = 0, offset = 0;
		while (source.toString().indexOf(strS) != -1) {
			start = source.toString().indexOf(strS);
			offset = start + strS.length();
			source.replace(start, offset, strD);
		}
		return source;
	}

	/**
	 * html转换
	 * @param strInput
	 * @return
	 */
	public static String HtmlEncode(String strInput) {
		String input = strInput;
		if ("".equals(input) || input==null ) {
			return "&nbsp;";
		} else {
			try {
				input = input.replaceAll("&", "&amp;");
				input = input.replaceAll("'", "&apos;");
				input = input.replaceAll("\"", "&quot;");
				input = input.replaceAll("<", "&lt;");
				input = input.replaceAll(">", "&gt;");
				input = input.replaceAll(" ", "&nbsp;");
				input = input.replaceAll("\r\n", "<br/>");
				input = input.replaceAll("\r", "<br/>");
				input = input.replaceAll("\n", "<br/>");
				//input = UBB.parseUbb(input);
			}catch(Exception e){
				e.printStackTrace();
			}
			return input;
		}
	}

	/**
	 * html转换
	 * @param strInput
	 * @return
	 */
	public static String HtmlReverse(String strInput) {
		String input = strInput;
		if ("".equals(input) || input==null) {
			return "";
		} else {
			input = input.replaceAll("&amp;", "&");
			input = input.replaceAll("&apos;", "'");
			input = input.replaceAll("&quot;", "\"");
			input = input.replaceAll("&lt;", "<");
			input = input.replaceAll("&gt;", ">");
			input = input.replaceAll("&nbsp;", " ");
			input = input.replaceAll("<br/>", "\r\n");
			input = input.replaceAll("<br/>", "\r");
			input = input.replaceAll("<br/>", "\n");
			return input;
		}
	}


	/**
	 * 得到GUID
	 * @return String 返回GUID
	 */
	public static String getGUID() {
		UID uid = new UID();
		return uid.toString();
	}

	/**
	 * 得到激活序列
	 * @return
	 */
	public static String getSerial(){
		UID uid1 = new UID();
		UID uid2 = new UID();

		return uid1.toString() + uid2.toString();
	}

	/**
	 * 格式化字符串
	 * @param strSource String 要格式化的字符串
	 * @param length int 格式化后的长度
	 * @param leftFill boolean 是否从左边填充，true，是，false，否
	 * @param fillChar char 要填充的字符
	 * @return String
	 * @author zfm
	 */
	public static String formatStr(String strSource, int length,
			boolean leftFill, char fillChar) {
		if (strSource.length() >= length) {
			return strSource;
		}
		StringBuffer strBuf = null;
		if (leftFill) {
			strBuf = new StringBuffer();
			for (int i = 0; i < length - strSource.length(); i++) {
				strBuf.append(fillChar);
			}
			strBuf.append(strSource);
		} else {
			strBuf = new StringBuffer(strSource);
			for (int i = 0; i < length - strSource.length(); i++) {
				strBuf.append(fillChar);
			}
		}
		return strBuf.toString();
	}

	public static String wToF(String aW) {
		String[] tmp =
			new String[] {"０", "１", "２", "３", "４", "５", "６", "７", "８", "９"};
		StringBuffer aW2 = new StringBuffer(aW);
		replaceAll(aW2, "．", ".");
		for (int i = 0; i <= 9; i++) {
			replaceAll(aW2, tmp[i], i + "");
		}
		return aW2.toString();
	}

	/**
	 *将数字转换成显示用字符串
	 *@param  number 数字
	 *@return String 显示用字符串
	 */
	public static String convertToShowNumber(int number, int length) {

		//数字格式器
		NumberFormat lotteryNumberFormat = NumberFormat.getInstance();

		//格式：强制2位整数，少位补0
		lotteryNumberFormat.setMaximumIntegerDigits(length);
		lotteryNumberFormat.setMinimumIntegerDigits(length);

		//接受格式化成果的字符串
		String showNumber = null;

		//执行格式化，将格式化结果传给字符串
		showNumber = lotteryNumberFormat.format(number);

		//返回字符串
		return showNumber;
	}

	/**
	 * 创建随机String的,由a-z组成
	 * @return String
	 */
	public static String getRandString() {
		int num = (int) (Math.random() * 100) + 1;
		num = num % 4 + 6; // 表示字符串的长度为6－10，这里的长度你可以用参数来控制
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < num; i++) {
			int j = (int) (Math.random() * 26);
			char c = (char) ('a' + j);
			sb.append(c);
		}
		return sb.toString();
	}

	/**
	 * 得到唯一ID编号
	 * @return String
	 */
	public static String getID() {
		String result = "";
		String currentTime = String.valueOf(System.currentTimeMillis()); //当前时间戳
		String randomString = getRandString(); //随机字符窜

		result = currentTime + randomString;
		return result;
	}


	/**
	 * 文件上传
	 * @param file
	 * @param req
	 * @param filePath
	 * @return
	 */
	public static boolean uploadFile(FormFile file,HttpServletRequest req,String filePath) {
		try {
			if (null != file.getFileName() && !file.getFileName().equals("")){
				InputStream stream = file.getInputStream();   //把文件读入   
				OutputStream bos = new FileOutputStream(filePath);//建立一个上传文件的输出流

				int bytesRead = 0;
				byte[] buffer = new byte[8192];
				while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
					bos.write(buffer, 0, bytesRead);//将文件写入服务器
				}
				bos.close();
				stream.close();
				return true;
			}
			else {
				return false;
			}
		} catch (Exception e) {  
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 生成缩略图
	 * @param filePath
	 * @return
	 */
	public static void genFileMin(String filePath, int tagSize){
		try{
			if(tagSize >0){
				java.io.File file = new java.io.File(filePath); //读入刚才上传的文件
				//String newUrl = filePath.substring(0, filePath.lastIndexOf(".")) + "_" +tagSize; //更改文件名，和扩展名,新的缩略图保存地址
				String newUrl = filePath + "_" + tagSize;
				Image src = javax.imageio.ImageIO.read(file); //构造Image对象
				double old_w=src.getWidth(null); //得到源图宽
				double old_h=src.getHeight(null); 
				int new_w=0;
				int new_h=0; //得到源图长
				double tempDouble; 
				if(old_w>old_h){
					tempDouble=old_w/tagSize;
				}else{
					tempDouble=old_h/tagSize;
				}
				new_w=(int) Math.round(old_w/tempDouble);
				new_h=(int) Math.round(old_h/tempDouble);//计算新图长宽
				BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
				tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
				FileOutputStream newImage=new FileOutputStream(newUrl); //输出到文件流
				JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newImage); 
				encoder.encode(tag); //近JPEG编码
				newImage.close(); 
			}else{ //如果是<0,原图转为jpg。
				java.io.File file = new java.io.File(filePath); //读入刚才上传的文件
				//String newUrl = filePath.substring(0, filePath.lastIndexOf(".")) +".jpg"; //更改文件名，和扩展名,新的缩略图保存地址
				String newUrl = filePath + "_" + tagSize;
				Image src = javax.imageio.ImageIO.read(file); //构造Image对象
				double old_w=src.getWidth(null); //得到源图宽
				double old_h=src.getHeight(null); 
				int new_w=(int) Math.round(old_w);
				int new_h=(int) Math.round(old_h); //得到源图长
				/*
			    double tempDouble; 
			    if(old_w>old_h){
			    	tempDouble=old_w/tagSize;
			    }else{
			    	tempDouble=old_h/tagSize;
			    }
			    new_w=(int) Math.round(old_w/tempDouble);
			    new_h=(int) Math.round(old_h/tempDouble);//计算新图长宽*/
				BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
				tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图
				FileOutputStream newImage=new FileOutputStream(newUrl); //输出到文件流
				JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newImage); 
				encoder.encode(tag); //近JPEG编码
				newImage.close(); 
			}
		}catch (Exception e) {  
			e.printStackTrace();
		}
	}

	/**
	 * 生成缩略图
	 * @param filePath
	 * @param scalex
	 * @param scaley
	 */
	public static void genFileMinByMagick(String filePath, int scalex, int scaley){
		//取得原文件
		try {     
			System.setProperty("jmagick.systemclassloader","no");
			MagickImage image = new MagickImage(new ImageInfo(filePath) );                       
			MagickImage small =  image.scaleImage(scalex,scaley);
			String newUrl = filePath + "_" + scalex;
			small.setFileName(newUrl);
			small.writeImage( new ImageInfo() );   	
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * 得到一页数据的SQL
	 * @param sql
	 * @param startIndex
	 * @param size
	 * @return
	 */
	public static String getPageSQL(String sql, int startIndex, int size){
		StringBuffer querySQL = new StringBuffer();
		querySQL.append(sql)
		.append(" limit ")
		.append(startIndex-1 )
		.append(",").append(size);
		return querySQL.toString();
	}

	/**
	 * 生成用户序列号
	 * @return
	 */
	public static String genUserSerial(){
		String result = "";
		String guid = getGUID(); //guid
		String currentTime = String.valueOf(System.currentTimeMillis()); //当前时间戳
		String randomString = getRandString(); //随机字符窜

		result = guid + currentTime + randomString;
		return result;
	}

	/**
	 * 读取文件到String
	 * @param f
	 * @return
	 * @throws IOException
	 */
	public static String loadAFileToString(File f) throws IOException {
		BufferedReader br = null;
		String ret = null;
		try {
			InputStreamReader  read = new InputStreamReader (new FileInputStream(f),"UTF-8");
			br =  new BufferedReader(read);
			String line = null;
			StringBuffer sb = new StringBuffer((int)f.length());
			while( (line = br.readLine() ) != null ) {
				sb.append(line).append("\n");
			}
			ret = sb.toString();
		} finally {
			if(br!=null) {try{br.close();} catch(Exception e){} }
		}
		return ret;       
	}

	/**
	 * 4舍5入转换函数
	 * @param dSource
	 * @return
	 */
	public static int getRound(float dSource){
		//BigDecimal的构造函数参数类型是double
		BigDecimal deSource = new BigDecimal(dSource);
		//deSource.setScale(0,BigDecimal.ROUND_HALF_UP) 返回值类型 BigDecimal
		//intValue() 方法将BigDecimal转化为int
		int iRound= deSource.setScale(0,BigDecimal.ROUND_HALF_UP).intValue();
		return iRound;
	} 

	public static void main(String[] args){

		Calendar cal = Calendar.getInstance(); 
		
		Timestamp a = Timestamp.valueOf("2007-4-4 12:12");
	}
	/**
	 * 获得windows路径
	 * @return String
	 */
	public static String getWinPath() {
		StringBuffer winpath  = new StringBuffer();
		try {
			Runtime r = Runtime.getRuntime();   
			Process p = r.exec("cmd.exe /c echo %SystemRoot%");   
			BufferedReader bf = new BufferedReader(new InputStreamReader(p.getInputStream()));   
			String line = "";   
			while ((line = bf.readLine()) != null)   
				winpath.append(line);
		}catch   (Exception   e){   
			e.printStackTrace();   
		} 

		return winpath.toString();
	}
}
